
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from ops import StringT, NumberT
from ops import OutputItem, CancelException

import properties
import os.path
import time # for making file names

from geotiffprops import Ui_GeoTiff

class GeoTiff(OutputItem):
    name = "geotiff"
    def __init__(self,x,y):
        OutputItem.__init__(self,x,y,["In"],[],"GeoTiff")
        self.propsDialog = Ui_GeoTiff()
        self.setToolTip("Save a GeoTiff File")
        self.inputs[0].value=None
        self.props = {'folder': os.path.realpath(os.path.curdir), 'filename': "output"}
        if not self.properties():
            raise CancelException
    def displayText(self):
        return "GeoTiff"
    def propDef(self):
        return {'folder': StringT, 'filename': StringT}

    def folderButtonClicked(self):
        dir = QFileDialog.getExistingDirectory(None, "Location for output",
                                               self.d.ui.folder.text(),
                                               QFileDialog.ShowDirsOnly)
        if dir:
            self.d.ui.folder.setText(dir)

    def properties(self):
        self.d = properties.dialog(self.propsDialog)
        QObject.connect(self.d.ui.folderButton,SIGNAL("clicked()"),self.folderButtonClicked)

        # set dialog from object's values
        self.setDialogValues(self.d.ui)
        if properties.show(self.d):
            command = CommandEditOutputGeoTiff(self,self.getDialogValues(self.d.ui))
            if self.scene():
                self.scene().undoStack.push(command)
            else:
                command.redo()
            return True
        else:
            return False

    def process(self):
        tm_year,tm_mon,tm_mday,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst = time.localtime()
        tag = "%04d%02d%02d%02d%02d%02d" % (tm_year,tm_mon,tm_mday,tm_hour,tm_min,tm_sec)
        fullName = str(self.props['filename'])+'-'+tag+os.path.extsep+"tif"
        fullPath = os.path.join(str(self.props['folder']),fullName)
        self.inputs[0].value.saveFile(fullPath)

class CommandEditOutputGeoTiff(QUndoCommand):
    def __init__(self,item,newValues):
        QUndoCommand.__init__(self,"Edit GeoTiff Output")
        self.newValues = newValues
        self.item = item
        self.oldValues = item.props
    def redo(self):
        item = self.item
        item.props = self.newValues
    def undo(self):
        item = self.item
        item.props = self.oldValues

